<template>
    <div class="achievements-page">
        <!-- 导航栏 -->
        <van-nav-bar title="Achievements" left-arrow @click-left="goBack" fixed>
            <template #right>
                <van-icon name="info-o" @click="showAchievementInfo" />
            </template>
        </van-nav-bar>

        <!-- 成就概览 -->
        <div class="achievements-overview">
            <div class="stats-cards">
                <div class="stat-card">
                    <div class="stat-icon">
                        <van-icon name="trophy-o" />
                    </div>
                    <div class="stat-info">
                        <div class="stat-number">{{ unlockedCount }}</div>
                        <div class="stat-label">Unlocked</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">
                        <van-icon name="diamond-o" />
                    </div>
                    <div class="stat-info">
                        <div class="stat-number">{{ totalPoints }}</div>
                        <div class="stat-label">Points</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">
                        <van-icon name="fire-o" />
                    </div>
                    <div class="stat-info">
                        <div class="stat-number">{{ currentStreak }}</div>
                        <div class="stat-label">Day Streak</div>
                    </div>
                </div>
            </div>

            <!-- 进度环 -->
            <div class="progress-ring">
                <van-circle :rate="completionRate" :speed="100" :stroke-width="8" color="#1989fa" layer-color="#f5f5f5"
                    :size="120">
                    <div class="progress-content">
                        <div class="progress-percentage">{{ Math.round(completionRate) }}%</div>
                        <div class="progress-label">Complete</div>
                    </div>
                </van-circle>
            </div>
        </div>

        <!-- 筛选标签 -->
        <div class="filter-section">
            <van-tabs v-model:active="activeFilter" @change="handleFilterChange">
                <van-tab title="All" name="all" />
                <van-tab title="Unlocked" name="unlocked" />
                <van-tab title="In Progress" name="progress" />
                <van-tab title="Locked" name="locked" />
            </van-tabs>
        </div>

        <!-- 成就分类 -->
        <div class="categories-section">
            <div class="category-tabs">
                <div v-for="category in categories" :key="category.id" class="category-tab"
                    :class="{ active: selectedCategory === category.id }" @click="selectedCategory = category.id">
                    <van-icon :name="category.icon" />
                    <span>{{ category.name }}</span>
                </div>
            </div>
        </div>

        <!-- 成就列表 -->
        <div class="achievements-content">
            <van-loading v-if="loading" size="24px" vertical>Loading achievements...</van-loading>
            <div v-else-if="filteredAchievements.length > 0" class="achievements-grid">
                <AchievementCard v-for="achievement in filteredAchievements" :key="achievement.id"
                    :achievement="achievement" @click="showAchievementDetail" @share="shareAchievement" />
            </div>
            <van-empty v-else description="No achievements found" image="search">
                <van-button type="primary" @click="clearFilters">
                    Clear Filters
                </van-button>
            </van-empty>
        </div>

        <!-- 成就详情弹窗 -->
        <van-popup v-model:show="showDetailPopup" position="center" round>
            <AchievementDetailModal v-if="showDetailPopup && selectedAchievement" :achievement="selectedAchievement"
                @close="showDetailPopup = false" />
        </van-popup>

        <!-- 成就解锁动画弹窗 -->
        <van-popup v-model:show="showUnlockAnimation" position="center" round>
            <AchievementUnlock v-if="showUnlockAnimation && unlockedAchievement" :achievement="unlockedAchievement"
                @close="showUnlockAnimation = false" />
        </van-popup>

        <!-- 信息弹窗 -->
        <van-popup v-model:show="showInfoPopup" position="bottom" :style="{ height: '60%' }" round>
            <div class="info-modal">
                <div class="info-header">
                    <h3>About Achievements</h3>
                    <van-icon name="cross" @click="showInfoPopup = false" />
                </div>
                <div class="info-content">
                    <div class="info-section">
                        <h4>How to Earn Achievements</h4>
                        <p>Complete training sessions, participate in community activities, and reach milestones to
                            unlock
                            achievements and earn points.</p>
                    </div>
                    <div class="info-section">
                        <h4>Achievement Types</h4>
                        <div class="achievement-types">
                            <div class="type-item">
                                <van-icon name="chat-o" />
                                <span>Communication</span>
                            </div>
                            <div class="type-item">
                                <van-icon name="manager-o" />
                                <span>Leadership</span>
                            </div>
                            <div class="type-item">
                                <van-icon name="friends-o" />
                                <span>Community</span>
                            </div>
                            <div class="type-item">
                                <van-icon name="fire-o" />
                                <span>Consistency</span>
                            </div>
                        </div>
                    </div>
                    <div class="info-section">
                        <h4>Points & Rewards</h4>
                        <p>Earn points to unlock special badges, climb the leaderboard, and access exclusive content and
                            features.</p>
                    </div>
                </div>
            </div>
        </van-popup>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
// import { motivationApi } from '@/api' // 暂时注释掉，实际项目中会用到
import type { Achievement } from '@/api/achievement'
import AchievementCard from '@/components/AchievementCard.vue'
import AchievementDetailModal from '@/components/AchievementDetailModal.vue'
import AchievementUnlock from '@/components/AchievementUnlock.vue'

const router = useRouter()

// 响应式数据
const loading = ref(true)
const activeFilter = ref('all')
const selectedCategory = ref(0) // 0 表示所有分类
const achievements = ref<Achievement[]>([])
const showDetailPopup = ref(false)
const showUnlockAnimation = ref(false)
const showInfoPopup = ref(false)
const selectedAchievement = ref<Achievement | null>(null)
const unlockedAchievement = ref<Achievement | null>(null)

// 统计数据
const currentStreak = ref(7)

// 分类数据
const categories = ref([
    { id: 0, name: 'All', icon: 'apps-o' },
    { id: 1, name: 'Communication', icon: 'chat-o' },
    { id: 2, name: 'Leadership', icon: 'manager-o' },
    { id: 3, name: 'Community', icon: 'friends-o' },
    { id: 4, name: 'Consistency', icon: 'fire-o' },
    { id: 5, name: 'Special', icon: 'star-o' }
])

// 模拟成就数据
const initializeMockData = () => {
    achievements.value = [
        {
            id: 1,
            title: 'First Steps',
            description: 'Complete your first training session',
            icon_url: '/achievement-first-steps.png',
            points: 100,
            is_unlocked: true,
            is_featured: false,
            category_id: 1,
            unlocked_at: '2024-10-20T14:30:00Z'
        },
        {
            id: 2,
            title: 'Communication Master',
            description: 'Achieve an average score of 8+ in communication scenarios',
            icon_url: '/achievement-communication.png',
            points: 500,
            is_unlocked: false,
            is_featured: true,
            category_id: 1,
            progress: {
                current: 6,
                target: 10
            },
            requirements: [
                'Complete 10 communication training sessions',
                'Maintain an average score of 8 or higher',
                'Receive positive feedback from 5 different scenarios'
            ]
        },
        {
            id: 3,
            title: 'Team Player',
            description: 'Successfully complete 5 team collaboration scenarios',
            icon_url: '/achievement-team.png',
            points: 300,
            is_unlocked: true,
            is_featured: false,
            category_id: 2,
            unlocked_at: '2024-10-19T16:45:00Z'
        },
        {
            id: 4,
            title: 'Consistent Learner',
            description: 'Train for 7 consecutive days',
            icon_url: '/achievement-streak.png',
            points: 250,
            is_unlocked: false,
            is_featured: false,
            category_id: 4,
            progress: {
                current: 7,
                target: 7
            }
        },
        {
            id: 5,
            title: 'Community Helper',
            description: 'Help 10 community members with their questions',
            icon_url: '/achievement-helper.png',
            points: 400,
            is_unlocked: false,
            is_featured: false,
            category_id: 3,
            progress: {
                current: 3,
                target: 10
            }
        },
        {
            id: 6,
            title: 'Negotiation Expert',
            description: 'Master all negotiation scenarios with perfect scores',
            icon_url: '/achievement-negotiation.png',
            points: 750,
            is_unlocked: false,
            is_featured: true,
            category_id: 1,
            progress: {
                current: 2,
                target: 8
            }
        },
        {
            id: 7,
            title: 'Social Butterfly',
            description: 'Make 50 connections in the community',
            icon_url: '/achievement-social.png',
            points: 350,
            is_unlocked: false,
            is_featured: false,
            category_id: 3,
            progress: {
                current: 23,
                target: 50
            }
        },
        {
            id: 8,
            title: 'Leadership Pioneer',
            description: 'Complete all leadership training modules',
            icon_url: '/achievement-leadership.png',
            points: 600,
            is_unlocked: false,
            is_featured: false,
            category_id: 2,
            progress: {
                current: 4,
                target: 12
            }
        }
    ] as Achievement[]
}

// 计算属性
const unlockedCount = computed(() => {
    return achievements.value.filter(a => a.is_unlocked).length
})

const totalPoints = computed(() => {
    return achievements.value
        .filter(a => a.is_unlocked)
        .reduce((sum, a) => sum + (a.points || 0), 0)
})

const completionRate = computed(() => {
    if (achievements.value.length === 0) return 0
    return (unlockedCount.value / achievements.value.length) * 100
})

const filteredAchievements = computed(() => {
    let filtered = achievements.value

    // 分类筛选
    if (selectedCategory.value > 0) {
        filtered = filtered.filter(a => a.category_id === selectedCategory.value)
    }

    // 状态筛选
    switch (activeFilter.value) {
        case 'unlocked':
            filtered = filtered.filter(a => a.is_unlocked)
            break
        case 'progress':
            filtered = filtered.filter(a => !a.is_unlocked && a.progress)
            break
        case 'locked':
            filtered = filtered.filter(a => !a.is_unlocked && !a.progress)
            break
    }

    return filtered
})

// 方法
const loadAchievements = async () => {
    try {
        loading.value = true
        // const response = await motivationApi.getAchievements()
        // achievements.value = response.data

        // 模拟API延迟
        await new Promise(resolve => setTimeout(resolve, 500))
    } catch (error) {
        console.error('Failed to load achievements:', error)
        showToast('Failed to load achievements')
    } finally {
        loading.value = false
    }
}

const handleFilterChange = (name: string) => {
    // 筛选逻辑已在计算属性中处理
}

const showAchievementDetail = (achievement: Achievement) => {
    selectedAchievement.value = achievement
    showDetailPopup.value = true
}

const shareAchievement = async (achievement: Achievement) => {
    try {
        if (navigator.share) {
            await navigator.share({
                title: `I unlocked "${achievement.title}"!`,
                text: `Check out my achievement in Social Dojo: ${achievement.description}`,
                url: window.location.href
            })
        } else {
            await navigator.clipboard.writeText(
                `I unlocked "${achievement.title}" in Social Dojo! ${window.location.href}`
            )
            showToast('Achievement shared to clipboard!')
        }
    } catch (error) {
        console.error('Failed to share achievement:', error)
        showToast('Failed to share achievement')
    }
}

const clearFilters = () => {
    activeFilter.value = 'all'
    selectedCategory.value = 0
}

const showAchievementInfo = () => {
    showInfoPopup.value = true
}

const goBack = () => {
    router.back()
}

// 模拟成就解锁
const simulateUnlock = () => {
    const lockedAchievements = achievements.value.filter(a => !a.is_unlocked)
    if (lockedAchievements.length > 0) {
        const achievement = lockedAchievements[0]
        if (achievement) {
            achievement.is_unlocked = true
            achievement.unlocked_at = new Date().toISOString()
            unlockedAchievement.value = achievement
            showUnlockAnimation.value = true
        }
    }
}

// 生命周期
onMounted(() => {
    initializeMockData()
    loadAchievements()

    // 模拟成就解锁（仅用于演示）
    setTimeout(() => {
        simulateUnlock()
    }, 3000)
})
</script>

<style lang="scss" scoped>
.achievements-page {
    min-height: 100vh;
    background: #f7f8fa;
    padding-top: 46px;

    .achievements-overview {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 24px 20px;

        .stats-cards {
            display: flex;
            justify-content: space-between;
            margin-bottom: 24px;

            .stat-card {
                display: flex;
                align-items: center;
                gap: 8px;

                .stat-icon {
                    .van-icon {
                        font-size: 24px;
                        color: #ffd21e;
                    }
                }

                .stat-info {
                    .stat-number {
                        font-size: 20px;
                        font-weight: 700;
                        line-height: 1;
                    }

                    .stat-label {
                        font-size: 12px;
                        opacity: 0.8;
                    }
                }
            }
        }

        .progress-ring {
            display: flex;
            justify-content: center;

            .progress-content {
                text-align: center;

                .progress-percentage {
                    font-size: 24px;
                    font-weight: 700;
                    color: #323233;
                }

                .progress-label {
                    font-size: 12px;
                    color: #646566;
                }
            }
        }
    }

    .filter-section {
        background: white;
        border-bottom: 1px solid #ebedf0;
    }

    .categories-section {
        background: white;
        padding: 16px 20px;
        border-bottom: 1px solid #ebedf0;

        .category-tabs {
            display: flex;
            gap: 8px;
            overflow-x: auto;
            padding-bottom: 4px;

            .category-tab {
                display: flex;
                flex-direction: column;
                align-items: center;
                padding: 8px 12px;
                background: #f7f8fa;
                border-radius: 8px;
                cursor: pointer;
                transition: all 0.3s ease;
                white-space: nowrap;

                &:hover {
                    background: #e8f3ff;
                }

                &.active {
                    background: #1989fa;
                    color: white;
                }

                .van-icon {
                    font-size: 18px;
                    margin-bottom: 4px;
                }

                span {
                    font-size: 12px;
                }
            }
        }
    }

    .achievements-content {
        padding: 20px;

        .achievements-grid {
            display: grid;
            grid-template-columns: 1fr;
            gap: 16px;
        }
    }

    .info-modal {
        height: 100%;
        display: flex;
        flex-direction: column;

        .info-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px;
            border-bottom: 1px solid #ebedf0;

            h3 {
                font-size: 18px;
                font-weight: 600;
                color: #323233;
                margin: 0;
            }

            .van-icon {
                color: #969799;
                cursor: pointer;
            }
        }

        .info-content {
            flex: 1;
            padding: 20px;
            overflow-y: auto;

            .info-section {
                margin-bottom: 24px;

                h4 {
                    font-size: 16px;
                    font-weight: 600;
                    color: #323233;
                    margin: 0 0 8px 0;
                }

                p {
                    font-size: 14px;
                    color: #646566;
                    line-height: 1.5;
                    margin: 0;
                }

                .achievement-types {
                    display: grid;
                    grid-template-columns: repeat(2, 1fr);
                    gap: 12px;
                    margin-top: 12px;

                    .type-item {
                        display: flex;
                        align-items: center;
                        gap: 8px;
                        padding: 8px;
                        background: #f7f8fa;
                        border-radius: 6px;

                        .van-icon {
                            color: #1989fa;
                            font-size: 16px;
                        }

                        span {
                            font-size: 13px;
                            color: #323233;
                        }
                    }
                }
            }
        }
    }
}
</style>